<?php
/*
Plugin Name: JayBo Nice Excerpt
Plugin URI: http://www.jaybowalkin.com/plugins/
Description: Beat the pants of the Wordpress standard excerpt function
Author: Bryan Clark
Version: 0.1
Author URI: http://www.jaybowalkin.com/
*/


function jaybo_nice_wp_trim_the_excerpt($text) {
	global $post;
	if ( '' == $text ) {
		$content = get_the_content('');
/*		$content = apply_filters('the_content', $content); don't apply the content filter until we work with the text */
		$text = str_replace(']]>', ']]&gt;', $content);
		$text = strip_tags($text);
/*    $text = preg_replace("/[^a-zA-Z0-9-\s]/", "", $text ); no need to strip out the non characters */
		$text = preg_replace('/\s\s+/', ' ', trim($text)); /* strip out multiple spaces like '  ' so the explode can work on only words */
		$excerpt_length = 60;
		$words = explode(' ', $text, $excerpt_length + 1);

		if (count($words) > $excerpt_length) {
      $word_to_find = $words[$excerpt_length - 1];
      $offset = strpos($content, $word_to_find, strlen($text));
      if ($offset === false) { 
        /* 
          if, for some reason we didn't get an offset from our helper starting point 
          of strlen($text) we should try from the begining since there could have been
          a lot of links and a little bit of text in the $content
       */
        $offset = strpos($content, $word_to_find, 0);
      }

      /* Starting from the word we found, look back to see if we are in an enclosing tag */
      $possible_gt_offset = strrpos(substr($content, 0, $offset), ">");
      /* Or did we just roll back over a new tag in that strpos above */
      $possible_lt_offset = strrpos(substr($content, 0, $offset), "<");
      /* If there is a tag enclosing to our left and the enclosing came before a new opening, we are inside of a tag */
      if ($possible_lt_offset !== false && ( $possible_gt_offset === false || $possible_lt_offset > $possible_gt_offset ) ) {
        /* Just leave out the tag and use the offset of before the tag as our new offset */
        $offset = $possible_lt_offset;
      }

      return apply_filters('the_content', balanceTags( substr( $content, 0,  $offset ) . "..." , true) );
		}
    return apply_filters('the_content', $content);

	}
  
	return $text;
}

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'jaybo_nice_wp_trim_the_excerpt');

function jaybo_nice_get_the_excerpt($fakeit = true) {
  global $post;
  $content = get_the_content();
  $content = apply_filters('the_content', $content);
  $excerpt = jaybo_nice_wp_trim_the_excerpt('');
  if ( $content == $excerpt ) {
    return $content;
  }
  return $excerpt . "<p><a class='read-more' href='" . get_permalink() . "'>Read the rest of this entry &raquo;</a></p>";
}

add_filter('the_excerpt', 'jaybo_nice_get_the_excerpt');

?>